'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  //获取所有的用户
  async index() {
    const { ctx, service } = this;
    const { Response, ResponseError, query } = ctx
    const res = new Response() //作为响应
    try {
      let users = null
      if(Object.keys(query).length === 0) { //获取所有
        users = await service.user.findAll()
        res.data = { users }
      }else { //条件匹配
        const { page = 1, limit = 10 } = query
        const where = {}
        if('page' in query && 'limit' in query){
          where.page = +page
          where.limit = +limit
        }
        res.data = await service.user.findAllByKeyWord(where)
      }
      res.message = '获取数据成功'
    }catch(e) {
      console.log(e)
      res.status = ctx.STATUS.ERROR;
			res.message = e;
    }
    ctx.body = res
  }

  //创建用户
  async create() {
    const { ctx, service } = this;
    const { Response, ResponseError, query, request: {body} } = ctx
    const res = new Response() //作为响应
    try {
      const { password = '123456' , nickname } = body
      const user = await service.user.findByFields({nickname})
      if(user && user.status === '1'){
        throw new ResponseError('用户已经存在')
      }else if(user && user.status === '0') {
        user.status = '1'
        await user.save();
        res.message = '解锁用户成功'
      }else {//用户没有记录
        await service.user.create({
          nickname,
          password
        })
        res.message = '创建用户成功'
      }
    }catch(e) {
      console.log(e.message)
      res.status = ctx.STATUS.ERROR;
			res.message = e;
    }
    ctx.body = res
  }

  //删除用户
  async destroy() {
    const { ctx, service } = this;
    const { Response, ResponseError, params } = ctx
    const res = new Response() //作为响应
    try {
      const {id: user_id} = params
      await service.user.softDestroy(user_id)
      res.message = '锁定用户成功'
    }catch(e) {
      console.log(e)
      res.status = ctx.STATUS.ERROR;
			res.message = e;
    }
    ctx.body = res
  }

  //更新用户
  async update() {
    const { ctx, service } = this;
    const { Response, ResponseError, params, request: {body} } = ctx
    const res = new Response() //作为响应
    try {
      const {id: user_id} = params
      const { UPDATE } = body
      await service.user.update(user_id, UPDATE)
      res.message = '更新用户成功'
    }catch(e) {
      console.log(e)
      res.status = ctx.STATUS.ERROR;
			res.message = e;
    }
    ctx.body = res
  }
}

module.exports = UserController;
